# -*- coding: UTF-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
from playsound import playsound

import time,json,requests,threading,socket,random,os,sys,subprocess,re

demoinit=open("../demo.json","r")
demoinit=demoinit.read()
demoinit=json.loads(demoinit)
url=demoinit["site"]+"/api/getdemo.php"
demo=requests.get(url)
demo=json.loads(demo.text)
doub=requests.get(demo["site"]+"/api/run.php")
doub=json.loads(doub.text)
# driver = webdriver.Firefox()
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Chrome(options=chrome_options)
pattern='(?<=(距离封盘<span class="sc-1f30fun-3 gDwIIO">)).*(?=</span></span><span class="sc-1f30fun-1 fGQfov">)'

def call():
	try:
		result=""
		result=subprocess.run(["python3","build.py"])
	except subprocess.TimeoutExpired as e:
		print(f"pull fuild")
	else:
		print("Update Successfully")
	# install
	try:
		result=""
		result=subprocess.run(["python3","pipinstall.py"])
	except subprocess.TimeoutExpired as e:
		print(f"install fuild")
	else:
		print("pip packages install successfully")

def head():
	global pattern
	driver.get('https://www.5199.vip/')
	username=demo["username"]
	password=demo["password"]
	# time.sleep(5)
	login_type=int(sys.argv[1])
	if login_type==1:
		while True:
			try:
				lg_u=driver.find_element(By.CSS_SELECTOR,".login-wrapper .input.username input")
				lg_u.click()
				for x in username:
					lg_u.send_keys(x)
				lg_pass=driver.find_element(By.CSS_SELECTOR,".login-wrapper .input.password input")
				lg_pass.click()
				for x in password:
					lg_pass.send_keys(x)
				lgc=driver.find_element(By.CSS_SELECTOR,".login-wrapper #loginBtn")
				lgc.click()
				time.sleep(demo["login_time2"])
			except Exception as e:
				print("登录失败，正在重试...")
			else:
				break

		while True:
			try:
				ex=""
				iframe=driver.find_element(By.ID,"agreement-frame")
				driver.switch_to.frame(iframe)
				ex=driver.find_element(By.CSS_SELECTOR,".sc-143ld7g-4.hPGgHr #auth-agreement-agree")
				ex.click()
			except Exception as e:
				pass
				# print("获取元素失败，正在重试...(1)")
			else:
				break

		driver.switch_to.default_content()
		while True:
			try:
				ex=""
				ex=driver.find_element(By.CSS_SELECTOR,".ant-modal-content .ant-modal-close")
				ex.click()
			except Exception as e:
				pass
				# print("获取元素失败，正在重试...(2)")
			else:
				break

		while True:
			try:
				game=driver.find_element(By.CSS_SELECTOR,'.sc-1mw5svm-0 .sc-cukfm7-1.eCkSMs div[data-rbd-draggable-id="menu-PK10JSC"]')
				game.click()
			except Exception as e:
				pass
				# print("获取元素失败，正在重试...(3)")
			else:
				break
		time.sleep(10)
	else:
		time.sleep(demo["login_time"])

	pk=0
	while True:
		try:
			es=""
			es=driver.find_element(By.CSS_SELECTOR,".sc-1f30fun-0.jlskun").get_attribute('outerHTML')
			es=re.search(pattern=pattern,string=es,flags=0)
			es=es.group()
			es=es.strip()
			print(es)
		except Exception as e:
			print("error status 1")

		else:	

			if es != "已封盘" :
	
				while True:
					try:
						es=""
						es=driver.find_element(By.CSS_SELECTOR,".sc-1f30fun-0.jlskun").get_attribute('outerHTML')
						es=re.search(pattern=pattern,string=es,flags=0)
						es=es.group()
						es=es.strip()
						print(es)
					except Exception as e:
						print("error status 2")	
					else:
						
						if es =="已封盘":
					
							while True:
								try:
									es=""
									es=driver.find_element(By.CSS_SELECTOR,".sc-1f30fun-0.jlskun").get_attribute('outerHTML')
									es=re.search(pattern=pattern,string=es,flags=0)
									es=es.group()
									es=es.strip()
									print(es)
								except Exception as e:
									print("error status 3")
								else:
									
									if es != "已封盘":
							
										pk=1
										break
					if pk==1:
						break
		if pk==1:
			break
	print("starting...")
def make():
	tree={}
	tree=requests.get(demo["site"]+"/api/gettree.php")
	tree=json.loads(tree.text)
	for a in range(0,len(tree)):
		time.sleep(0.5)
		for b in range(0,len(tree[a]["tree"])):
			if len(tree[a]["tree"][b]["order"])>0:
				for c in range(0,len(tree[a]["tree"][b]["order"])):
					dom=""
					money=tree[a]["tree"][b]["order"][c]["money"]
					moneys=str(money)
					dom=tree[a]["trackdom"]+tree[a]["tree"][b]["projectdom"]
					try:
						element=driver.find_element(By.CSS_SELECTOR,dom)
						element.click()
						elemen=driver.find_element(By.CSS_SELECTOR,dom)
						for x in moneys:
							elemen.send_keys(x)
						print(moneys)
					except Exception as e:
						print("error!!!")
					
			else :
				continue
	try:
		el=driver.find_element(By.CSS_SELECTOR,".sc-2bhkbz-0.fBmSuo .sc-2bhkbz-1.kVjCHR .sc-1iw0f4-0.gmwSkA.sc-heq5nv-0.sc-2bhkbz-6.hAIctb.fjBrls")
		el.click()
	except Exception as e:
		print("error!!!")
	time.sleep(1)
	try:
		els=driver.find_element(By.CSS_SELECTOR,".sc-uoa0md-1.gYfFKC .sc-1iw0f4-0.gmwSkA.sc-heq5nv-0.sc-19tubnh-0.hAIctb.kfaAmq")
		els.click()
	except Exception as e:
		print("error!!!")
	time.sleep(1)

def sel():
	global pattern
	i=0
	while True:
		status=0
		while True:
			try:
				es=""
				es=driver.find_element(By.CSS_SELECTOR,".sc-1f30fun-0.jlskun").get_attribute('outerHTML')
				es=re.search(pattern=pattern,string=es,flags=0)
				es=es.group()
				es=es.strip()
			except Exception as e:
				if status==5:
					driver.refresh()
					break
				status=status+1
				print("获取当前状态失败,正在重新执行中...")
			else:
				break

		if es != "已封盘":
			if i<1:
				i=i+1
			elif i<3 and i==2:
				i=i+1
		elif es == "已封盘":
			if i<2 and i==1:
				i=i+1
		if i==3:
			break
	time.sleep(1)
	print("starting...")
	url=demo["site"]+"/api/copyorder.php"
	res=requests.get(url)
	
def pk(x):
	print(x)
	if x > 1:
		if x==2:
			url=demo["site"]+"/api/vk.php?vk=1"
			requests.get(url)
		while True:
			qh=""
			jm=""
			d={}
			qh=driver.find_element(By.CSS_SELECTOR,".sc-1ixr2qq-1.eiwGGm .sc-1ixr2qq-3.kjvYbP")
			jm=driver.find_element(By.CSS_SELECTOR,".sc-l0mymw-1.kNHxYF").get_attribute('outerHTML')
			d={"qh":qh.text,"jm":jm}
			url=demo["site"]+"/api/pkresult.php?qh="+qh.text+"&jm="+jm
			res=requests.post(url=url,data=d)
			restext=json.loads(res.text)
			print(restext)
			if restext["code"]==200:
				res=requests.post(url=url,data=d)
				break
		time.sleep(1)

def run():
	prev={}
	prev=requests.get(demo["site"]+"/api/prev.php")
	prev=json.loads(prev.text)
	pid=""
	money=0
	treeid=""
	issue=""
	url=demo["site"]+"/api/pid.php"
	pid=requests.get(url)
	pid=json.loads(pid.text)
	pid=pid["pid"]

	for x in range(0,len(prev)):
		while True:
			try:
				is_sue=driver.find_element(By.CSS_SELECTOR,".sc-1f30fun-0.jlskun span span.sc-1f30fun-2.EMCFi")
				is_sue=is_sue.text
				print(is_sue)
			except Exception as e:
				print("获取当前期号失败,正在重新执行中...")
			else:
				break
		is_sue=bytes(is_sue, 'utf-8')
		is_sue=is_sue.decode("utf-8")
		issue=is_sue.strip()
		# prev[x]["result"]="no"
		ispoin=prev[x]["poin"]
		if prev[x]["result"]=="no":
			treeid=prev[x]["tree_id"]
			if pid==0:
				pid=prev[x]["pid"]
			if ispoin+1==len(doub):
				money=doub[0]
				ispoined=0
			else:
				money=doub[ispoin+1]
				ispoined=ispoin+1
			victory(prev[x]["money"],"no")
		else:
			treeid=prev[x]["tree_id"]
			if pid==0:
				pid=prev[x]["pid"]
			money=doub[0]
			ispoined=0
			victory(prev[x]["money"],"yes")
		
		url=""
		url=demo["site"]+"/api/order.php?issue="+issue+"&treeid="+str(treeid)+"&pid="+str(pid)+"&money="+str(money)+"&poin="+str(ispoined)+"&id="+str(prev[x]["id"])
		requests.get(url)
	url=demo["site"]+"/api/auto.php"
	res=requests.get(url)

def victory(money,is_yes):
	url=demo["site"]+"/api/victory.php?victory="+str(money)+"&is_yes="+is_yes
	info=requests.get(url)
	info=json.loads(info.text)
	if info["msg"]=="stop" :
		print("已到达预停状态...")
		playsound("warning.mp3")
		time.sleep(1)
		print(3)
		time.sleep(1)
		print(2)
		time.sleep(1)
		print(1)
		time.sleep(1)
		print(0)
		print("按任意键退出")
		i=1
		while True:
			message=sys.stdin.readline()
			if message :
				break
			i=i+1
		exit()

def main():
	x=0
	while True:
		make()
		sel()
		pk(x)
		run()
		x=x+1

def userid():
	randoms=str(random.randint(111111,999999))
	return randoms

uid=userid()

def client():
	global uid
	while True:
		try:
			# time.sleep(1)
			client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			# 连接到服务器端
			client_socket.connect(('localhost', 8812))
			# 发送数据
			client_socket.sendall(uid.encode())
			# 接收服务器端响应
			data = client_socket.recv(1024)
			# print(f'Received: {data.decode()}')
			m=data.decode()
			if m.count("/"):
				s=m.split("/")
				if int(s[0])==int(uid): 
					os.system(s[1])
			else:
				print(f'Received: {data.decode()}')    
		finally:
			pass

if __name__ == '__main__':
	call()
	head()
	thread1=threading.Thread(target=main)
	thread2=threading.Thread(target=client)
	thread1.start()
	thread2.start()
	thread1.join()
	thread2.join()
